package com.kitty.game.equip.handler;

import com.kitty.game.role.model.Role;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.equip.message.RespStrengthenJewelrySuccess;
import com.kitty.mina.message.MessagePusher;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.*;
import java.util.HashSet;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import static com.kitty.game.utils.Const.*;
import static com.kitty.game.utils.NotifyModules.NOTIFY_EQUIP_STRENGTHEN_OK;
import com.kitty.game.equip.handler.UpgradeHandler;

/**
 * 首饰强化
 */
@Component("StrengthenJewelryHandler")
public class StrengthenJewelryHandler extends UpgradeHandler {
    private static final String ERROR_RESOURCES = "请放入正确的装备或材料。";
    private static final String MAX_STRENGTHEN_LEVEL = "当前首饰强化等级已达上限。";
    private static final int COST_EXP = 0;
    private static final int COST_CASH = 1000000;
    private static final String TRANSFORM_TIME = "本日已经进行过一次首饰强化了，请明日再来。";
    private static final String SUCCESS_MESSAGE = "强化成功。";
    private static final String FAIL_MESSAGE = "真遗憾，强化失败了，当前进度#R{0}%#n，当进度达到#R100%#n强化必定成功。";
    /**
     * 强化增加百分比的最大值 根据等级削减
     */
    private static final short FULL_PROGRESS = 10000;

    private short getStrengthenProgress(short strengthenLevel) {
        return (short) (FULL_PROGRESS / Math.pow(strengthenLevel + 2, 2));

    }

    /**
     * 随机增加一条首饰上的属性
     */
    private boolean randomAddField(RoleEquip roleEquip) {
        Random random = new Random();
        boolean isSuccess = random.nextInt(100) + 1 < 99;
        Set<FiedValue> fieldValues;
        if (random.nextBoolean()) {
            fieldValues = new HashSet<>(roleEquip.getFields().get((short) 514).getField().values());
        } else {
            fieldValues = new HashSet<>(roleEquip.getFields().get((short) 770).getField().values());
        }
        if (isSuccess) {
            for (FiedValue fieldValue : fieldValues) {
                int currValue = attrService.getValue(fieldValue.getValue());
                int maxValue = getMaxFieldByld(fieldValue.getType(), roleEquip.queryLevel(), roleEquip.queryEquipPos(false));
                if (currValue >= maxValue) {
                    isSuccess = false;
                    continue;
                }
                fieldValue.setValue(currValue + 1);
                isSuccess = true;
                break;
            }
        }
        return isSuccess;
    }

    @Override
    public String doUpgrade(Role role, Object... params) {
        RoleEquip roleEquip = (RoleEquip) params[0];
        RoleEquipField basicAttr = roleEquip.getFields().get((short) 258);

        role.setJewelryStrengthenCount(0);

        roleService.subtractMoney(role, COST_CASH);
        roleService.substractExp(role, COST_EXP);
        roleService.substractChargeScore(role, 10);

        short strengthenLevel = roleEquip.queryStrengthenLevel();
        short strengthenProgress = roleEquip.queryStrengthenProgress();
        strengthenProgress += getStrengthenProgress(strengthenLevel);
        roleEquip.alterStrengthenProgress(strengthenProgress);
        int rate = new Random().nextInt(150000);
        /**成功*/
        if (strengthenProgress >= FULL_PROGRESS || (rate < FULL_PROGRESS && strengthenProgress > 5000)) {
            /**强化成功了有几率增加其中一条属性的值*/
            boolean isChange = randomAddField(roleEquip);
            roleEquip.alterStrengthenProgress(0);
            /**因为首饰基础属性只有一条 所以只取第一条*/
            Optional<FiedValue> optional = basicAttr.getField().values().stream().findFirst();
            roleEquip.alterStrengthenLevel(strengthenLevel + 1);
            AtomicInteger oldValue = new AtomicInteger();
            optional.ifPresent(fieldValue -> oldValue.set(attrService.getValue(fieldValue.getValue())));
            int addValue = getJewelryDevelopValue(roleEquip.queryEquipPos(false));
            optional.ifPresent(fieldValue -> fieldValue.setValue(oldValue.intValue() + addValue));

            refreshRoleEquip(role, roleEquip);
            pushOperateResult(role, UPGRADE_SUCCESS);
            RespStrengthenJewelrySuccess jewelrySuccess = new RespStrengthenJewelrySuccess(roleEquip.getId(), isChange);
            MessagePusher.pushMessage(role, jewelrySuccess);
            return SUCCESS_MESSAGE;
        } else {
            /**失败增加进度*/
            refreshRoleEquip(role, roleEquip);
            RespStrengthenJewelrySuccess jewelrySuccess = new RespStrengthenJewelrySuccess(roleEquip.getId(), false);
            MessagePusher.pushMessage(role, jewelrySuccess);
            return MessageFormat.format(FAIL_MESSAGE, new DecimalFormat("#.00").format(strengthenProgress / 100d));
        }

    }

    @Override
    int getNotifyType() {
        return NOTIFY_EQUIP_STRENGTHEN_OK;
    }

    @Override
    public String acceptUpgrade(Role role, int upgradePos, String param) {
        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, upgradePos);
        if (roleEquip == null || roleEquip.queryLevel() < 120 || !isRightPosition(roleEquip.queryEquipPos(false))) {
            return ERROR_RESOURCES;
        }
        String content = checkResource(role, roleEquip);
        if (content != null) {
            return content;
        }

        return doUpgrade(role, roleEquip);
    }

    @Override
    boolean isRightPosition(byte equipPos) {
        return equipPos == NECKLACE || equipPos == BALDRIC || equipPos == LEFT_WRIST;
    }

    @Override
    public String checkResource(Object... objects) {
        Role role = (Role) objects[0];
        RoleEquip roleEquip = (RoleEquip) objects[1];
        if (role.getLevel() < 125) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, "等级");
        }
        if (role.getExp() < COST_EXP) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, "经验");
        }
        if (role.getMoney() < COST_CASH) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, "金钱");
        }
//        if (role.getJewelryStrengthenCount() >= 1) {
//            return MessageFormat.format(TRANSFORM_TIME, roleEquip.getName());
//        }
        if (roleEquip.queryStrengthenLevel() >= 20) {
            return MAX_STRENGTHEN_LEVEL;
        }
        RoleEquipField basicAttr = roleEquip.getFields().get((short) 258);
        if (basicAttr == null || basicAttr.getField().size() <= 0) {
            return ERROR_RESOURCES;
        }
        return null;
    }

    @Override
    public int needCash(short level, int pos) {
        return 0;
    }

    @Override
    public String getUpdateTypeStr() {
        return "strengthen_jewelry";
    }

    /**
     * 取首饰强化增加的属性
     */
    private int getJewelryDevelopValue(int jewelryType) {
        if (jewelryType == NECKLACE) {
            return 50;
        } else if (jewelryType == BALDRIC) {
            return 80;
        } else if (jewelryType == LEFT_WRIST) {
            return 10;
        }
        return 0;
    }

}
